package fire.and.near.challenger.camera;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.DisplayMetrics;
import android.util.Log;

public class CameraHelper {

	public static final int REQUEST_TAKE_PHOTO = 666;
	
	private CameraHelper() {}
	
	public static String dispatchTakePictureIntent(Activity context) {
	    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
	    String currentPhotoPath = null;

	    if (takePictureIntent.resolveActivity(context.getPackageManager()) != null) {

	        File photoFile = null;
	        try {
	            photoFile = createImageFile(context);
	            currentPhotoPath = photoFile.getAbsolutePath();
	        } catch (IOException ex) {
	            Log.i("CAMERA", "IOException: " + ex.getMessage());
	        }
	        
	        if (photoFile != null) {
	            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
	                    Uri.fromFile(photoFile));
	            takePictureIntent.putExtra(MediaStore.EXTRA_SCREEN_ORIENTATION, 
	            		ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
	            context.startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
	        }
	    }
	    return currentPhotoPath;
	}
	
	@SuppressLint("SimpleDateFormat")
	private static File createImageFile(Context context) throws IOException {

	    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
	    String imageFileName = "JPEG_" + timeStamp + "_";
	    File storageDir = null;
	    
	    if(isExternalStorageWritable()) {
	    	storageDir = context.getExternalFilesDir(
		            Environment.DIRECTORY_PICTURES);
	    } else {
			storageDir = context.getFilesDir();
		}
	
	    File image = File.createTempFile(
	        imageFileName,  /* prefix */
	        ".jpg",         /* suffix */
	        storageDir      /* directory */
	    );

	    return image;
	}
	
	public static int calculateInSampleSize(
            BitmapFactory.Options options, int reqWidth, int reqHeight) {

	    final int height = options.outHeight;
	    final int width = options.outWidth;
	    int inSampleSize = 1;
	
	    if (height > reqHeight || width > reqWidth) {
	
	        final int halfHeight = height / 2;
	        final int halfWidth = width / 2;

	        while ((halfHeight / inSampleSize) > reqHeight
	                && (halfWidth / inSampleSize) > reqWidth) {
	            inSampleSize *= 2;
	        }
	    }
	
	    return inSampleSize;
	}
	
	public static BitmapFactory.Options makeSampleOptions(Activity context, 
							BitmapFactory.Options options, 
							int reqWidth, 
							int reqHeight) {
		
		// dirty hack, used to correct 
		// the width and height for the sample preview
		DisplayMetrics metrics = new DisplayMetrics();
		context.getWindowManager()
						.getDefaultDisplay()
						.getMetrics(metrics);

		int altHeight = metrics.heightPixels;
		int altWidth = metrics.widthPixels;
		
		if (altHeight < altWidth) {
			int tmp = altHeight;
			altHeight = altWidth;
			altWidth = tmp;
		}
		
		altWidth = (int) Math.round(altWidth / 1.5);;
		altHeight = (int) Math.round(altHeight / 3);
		
		// End of hack
		
		Log.i("FRAGMENT_PHOTO", "" + altWidth + "x" + altHeight);
		options.inSampleSize = calculateInSampleSize(options,
				reqWidth == 0 ? altWidth : reqWidth, reqHeight == 0 ? altHeight : reqHeight);
		
		return options;
	}
	
	private static boolean isExternalStorageWritable() {
	    String state = Environment.getExternalStorageState();
	    if (Environment.MEDIA_MOUNTED.equals(state)) {
	        return true;
	    }
	    return false;
	}

	/* Checks if external storage is available to at least read */
	private static boolean isExternalStorageReadable() {
	    String state = Environment.getExternalStorageState();
	    if (Environment.MEDIA_MOUNTED.equals(state) ||
	        Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
	        return true;
	    }
	    return false;
	}
}
